﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Clmp.Data.DBEntity
{
    /// <summary>
    /// 数据库事务
    /// </summary>
    public class Transaction : IDisposable
    {
        public Transaction()
        {
            if (_isInit)
                isNested = true;
            else
                _isInit = true;
        }

        [ThreadStaticAttribute]
        private static bool _isInit;

        /// <summary>
        /// 是嵌套事务(嵌套事务执行Commit无效)
        /// </summary>
        private bool isNested = false;

        /// <summary>
        /// 事务是否初始化
        /// </summary>
        public static bool IsInit
        {
            get { return _isInit; }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void Commit()
        {
            if (!isNested)
                TransactionContext.DbTransaction.Commit();
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        public void Rollback()
        {
            TransactionContext.DbTransaction.Rollback();
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <param name="pointName">回滚点名称</param>
        public void Rollback(string pointName)
        {
            TransactionContext.DbTransaction.Rollback(pointName);
        }
        /// <summary>
        /// 创建回滚点
        /// </summary>
        /// <param name="savePointName">回滚点名称</param>
        public void Save(string savePointName)
        {
            TransactionContext.DbTransaction.Save(savePointName);
        }

        #region IDisposable 成员

        public void Dispose()
        {
            if (!isNested)
            {
                TransactionContext.Clear();
                _isInit = false;
            }
        }

        #endregion
    }
}
